package org.srunpass;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 *
 *
 * @author srunpass
 * @version Id: TextWebSocketFrameHandler, v 0.1 2025/7/14 17:17 srunpass Exp $
 */
public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private static final ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        Channel incoming = ctx.channel();
        group.writeAndFlush(new TextWebSocketFrame("[系统] 用户 " + incoming.remoteAddress() + " 加入聊天室"));
        group.add(incoming);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        Channel leaving = ctx.channel();
        group.writeAndFlush(new TextWebSocketFrame("[系统] 用户 " + leaving.remoteAddress() + " 离开聊天室"));
        group.remove(leaving);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) {
        Channel sender = ctx.channel();
        group.forEach(ch -> {
            if (ch != sender) {
                ch.writeAndFlush(new TextWebSocketFrame("[用户 " + sender.remoteAddress() + "]: " + msg.text()));
            } else {
                ch.writeAndFlush(new TextWebSocketFrame("[我]: " + msg.text()));
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
